package com.samsung.sbackup;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;

public class ScheduleSettings extends Activity {

	Button btnBack;
	Button btnSave;
	LinearLayout lnrOptions;
	LinearLayout lnrRepeatation;
	LinearLayout lnrTime;
	Switch swOnOff;
	TextView tvOnOff;
	TextView tvOptions;
	TextView tvRepeatation;
	TextView tvBackupTime;
	TextView tvBackupTimeHeader;
	TextView tvOptionsHeader;
	TextView tvRepeatationHeader;
	TextView tvOptionsSummary;
	String backupOptionsCode;

	SharedPreferences sharedPref;
	Editor prefEditor;
	Map<String, Integer> REPEATATION_MAPPING_PREF;
	Map<String, Integer> REPEATATION_MAPPING_DIALOG;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.schedule_settings);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		btnBack = (Button) findViewById(R.id.schedule_settings_btnBack);
		btnSave = (Button) findViewById(R.id.schedule_settings_btnSave);
		lnrOptions = (LinearLayout) findViewById(R.id.schedule_settings_linearOptions);
		lnrRepeatation = (LinearLayout) findViewById(R.id.schedule_settings_linearRepeatation);
		lnrTime = (LinearLayout) findViewById(R.id.schedule_settings_linearTime);
		swOnOff = (Switch) findViewById(R.id.schedule_settings_swOnOff);
		tvOnOff = (TextView) findViewById(R.id.schedule_settings_tvOnOff);
		tvOptions = (TextView) findViewById(R.id.schedule_settings_tvOptions);
		tvRepeatation = (TextView) findViewById(R.id.schedule_settings_tvRepeatation);
		tvBackupTime = (TextView) findViewById(R.id.schedule_settings_tvTime);
		tvOptionsHeader = (TextView) findViewById(R.id.schedule_settings_tvOptionsHeader);
		tvRepeatationHeader = (TextView) findViewById(R.id.schedule_settings_tvRepeatationHeader);
		tvBackupTimeHeader = (TextView) findViewById(R.id.schedule_settings_tvTimeHeader);
		tvOptionsSummary = (TextView) findViewById(R.id.schedule_settings_tvOptionsSummary);

		sharedPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		prefEditor = sharedPref.edit();

		// set map between tvOptions and pref repeatation
		REPEATATION_MAPPING_PREF = new HashMap<String, Integer>();
		REPEATATION_MAPPING_PREF.put("Every day", 1);
		REPEATATION_MAPPING_PREF.put("Every 3 days", 3);
		REPEATATION_MAPPING_PREF.put("Every week", 7);
		REPEATATION_MAPPING_PREF.put("Every month", 30);

		// set map between tvOptions and dialog index
		REPEATATION_MAPPING_DIALOG = new HashMap<String, Integer>();
		REPEATATION_MAPPING_DIALOG.put("Every day", 0);
		REPEATATION_MAPPING_DIALOG.put("Every 3 days", 1);
		REPEATATION_MAPPING_DIALOG.put("Every week", 2);
		REPEATATION_MAPPING_DIALOG.put("Every month", 3);

		btnBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// save enable/disable state
				prefEditor.putBoolean(
						FragmentSettingsPreference.SCHEDULE_BACKUP,
						swOnOff.isChecked());

				// save options state
				String code = "";
				// if code = 1000 -> backup contacts, do not backup sms,
				// calendar and apps
				if (tvOptions.getText().toString().contains("Contacts"))
					code += "1";
				else
					code += "0";

				if (tvOptions.getText().toString().contains("Sms"))
					code += "1";
				else
					code += "0";

				if (tvOptions.getText().toString().contains("Calendar"))
					code += "1";
				else
					code += "0";

				if (tvOptions.getText().toString().contains("Apps"))
					code += "1";
				else
					code += "0";

				prefEditor.putString(FragmentSettingsPreference.BACKUP_OPTIONS,
						code);

				// save repeatation state
				prefEditor.putInt(FragmentSettingsPreference.REPEATATION,
						REPEATATION_MAPPING_PREF.get(tvRepeatation.getText()
								.toString()));

				// save time state
				long tomorrow = Calendar.getInstance().getTimeInMillis() + 24 * 3600 * 1000;
				prefEditor.putString(FragmentSettingsPreference.BACKUP_TIME,
						ConvertToDate(tomorrow) + " "
								+ tvBackupTime.getText().toString());
				System.out.println(ConvertToDate(tomorrow) + " "
						+ tvBackupTime.getText().toString());

				// only need commit for the last time change prefEditor
				prefEditor.commit();

				// start schedule settings alarm counter if scheduleState = true
				AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				Intent intent = new Intent(ScheduleSettings.this,
						AlarmReceiver.class);
				PendingIntent pendingIntent = PendingIntent.getBroadcast(
						ScheduleSettings.this.getApplicationContext(), 0,
						intent, PendingIntent.FLAG_UPDATE_CURRENT);
				if (sharedPref.getBoolean(
						FragmentSettingsPreference.SCHEDULE_BACKUP, false)) {
					alarmManager
							.setRepeating(
									AlarmManager.RTC_WAKEUP,
									java.lang.System.currentTimeMillis()
											+ (Long.valueOf(Convert(sharedPref
													.getString(
															FragmentSettingsPreference.BACKUP_TIME,
															""))) - java.lang.System
													.currentTimeMillis()),
									Long.valueOf(sharedPref
											.getInt(FragmentSettingsPreference.REPEATATION,
													1)) * 1000 * 24 * 3600,
									pendingIntent);
				} else {
					alarmManager.cancel(pendingIntent);
				}
				finish();
			}
		});

		lnrOptions.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final Dialog dialog = new Dialog(ScheduleSettings.this);
				dialog.setContentView(R.layout.schedule_backup_options);
				dialog.setTitle("Options");

				Button dialogBtnSave = (Button) dialog
						.findViewById(R.id.schedule_backup_options_btnSave);
				Button btnCancel = (Button) dialog
						.findViewById(R.id.schedule_backup_options_btnCancel);
				final CheckBox cbContacts;
				final CheckBox cbSms;
				final CheckBox cbCalendar;
				final CheckBox cbApps;
				cbContacts = (CheckBox) dialog
						.findViewById(R.id.schedule_backup_options_cbContacts);
				cbSms = (CheckBox) dialog
						.findViewById(R.id.schedule_backup_options_cbSms);
				cbCalendar = (CheckBox) dialog
						.findViewById(R.id.schedule_backup_options_cbCalendar);
				cbApps = (CheckBox) dialog
						.findViewById(R.id.schedule_backup_options_cbApps);

				if (tvOptions.getText().toString().contains("Contacts"))
					cbContacts.setChecked(true);
				if (tvOptions.getText().toString().contains("Sms"))
					cbSms.setChecked(true);
				if (tvOptions.getText().toString().contains("Calendar"))
					cbCalendar.setChecked(true);
				if (tvOptions.getText().toString().contains("Apps"))
					cbApps.setChecked(true);

				dialogBtnSave.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String textView = "";
						if (cbContacts.isChecked())
							textView += "Contacts ";
						if (cbSms.isChecked())
							textView += "Sms ";
						if (cbCalendar.isChecked())
							textView += "Calendar ";
						if (cbApps.isChecked())
							textView += "Apps ";
						tvOptions.setText(textView);
						dialog.dismiss();
					}
				});

				btnCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.show();
			}
		});

		lnrRepeatation.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final CharSequence[] items = { "Every day", "Every 3 days",
						"Every week", "Every month" };
				// Creating and Building the Dialog
				AlertDialog dialog;
				AlertDialog.Builder builder = new AlertDialog.Builder(
						ScheduleSettings.this);
				builder.setTitle("Repeat backup");
				builder.setSingleChoiceItems(items, REPEATATION_MAPPING_DIALOG
						.get(tvRepeatation.getText().toString()),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {

								switch (item) {
								case 0:
									tvRepeatation.setText("Every day");
									break;
								case 1:
									tvRepeatation.setText("Every 3 days");
									break;
								case 2:
									tvRepeatation.setText("Every week");
									break;
								case 3:
									tvRepeatation.setText("Every month");
									break;
								}
								dialog.dismiss();
							}
						});
				dialog = builder.create();
				dialog.show();
			}
		});

		lnrTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String[] time = tvBackupTime.getText().toString().split(":");
				int hour = Integer.parseInt(time[0]);
				int minute = Integer.parseInt(time[1]);
				TimePickerDialog.OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						if (minute < 10)
							tvBackupTime.setText(String.valueOf(hourOfDay)
									+ ":0" + String.valueOf(minute));
						else
							tvBackupTime.setText(String.valueOf(hourOfDay)
									+ ":" + String.valueOf(minute));
					}

				};
				TimePickerDialog timePicker = new TimePickerDialog(
						ScheduleSettings.this, onTimeSetListener, hour, minute,
						true);
				timePicker.setTitle("Backup Time");
				timePicker.show();
			}
		});

		// init states
		initEnableState();
		initBackupOptionsState();
		initRepeatationState();
		initBackupTime();

	}

	private void initEnableState() {
		// init enable/disable state of schedule backup
		boolean scheduleBackupState = sharedPref.getBoolean(
				FragmentSettingsPreference.SCHEDULE_BACKUP, false);
		swOnOff.setChecked(scheduleBackupState);
		if (swOnOff.isChecked())
			tvOnOff.setText("Enabled");
		else {
			tvOnOff.setText("Disabled");

			lnrOptions.setClickable(false);
			lnrRepeatation.setClickable(false);
			lnrTime.setClickable(false);

			tvOptionsHeader.setTextColor(Color.LTGRAY);
			tvRepeatationHeader.setTextColor(Color.LTGRAY);
			tvBackupTimeHeader.setTextColor(Color.LTGRAY);
			tvOptionsSummary.setTextColor(Color.LTGRAY);
		}

		swOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					lnrOptions.setClickable(true);
					lnrRepeatation.setClickable(true);
					lnrTime.setClickable(true);

					tvOptionsHeader.setTextColor(Color.BLACK);
					tvRepeatationHeader.setTextColor(Color.BLACK);
					tvBackupTimeHeader.setTextColor(Color.BLACK);
					tvOptionsSummary.setTextColor(Color.BLACK);

					tvOnOff.setText("Enabled");
				} else {
					lnrOptions.setClickable(false);
					lnrRepeatation.setClickable(false);
					lnrTime.setClickable(false);

					tvOptionsHeader.setTextColor(Color.LTGRAY);
					tvRepeatationHeader.setTextColor(Color.LTGRAY);
					tvBackupTimeHeader.setTextColor(Color.LTGRAY);
					tvOptionsSummary.setTextColor(Color.LTGRAY);

					tvOnOff.setText("Disabled");
				}
			}
		});
	}

	private void initBackupOptionsState() {
		backupOptionsCode = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_OPTIONS, "1110");
		String textView = "";
		if (backupOptionsCode.charAt(0) == '1')
			textView += "Contacts ";
		if (backupOptionsCode.charAt(1) == '1')
			textView += "Sms ";
		if (backupOptionsCode.charAt(2) == '1')
			textView += "Calendar ";
		if (backupOptionsCode.charAt(3) == '1')
			textView += "Apps ";
		tvOptions.setText(textView);
	}

	private void initRepeatationState() {
		int initValue = sharedPref.getInt(
				FragmentSettingsPreference.REPEATATION, 7);
		if (initValue == 1)
			tvRepeatation.setText("Every day");
		if (initValue == 3)
			tvRepeatation.setText("Every 3 days");
		if (initValue == 7)
			tvRepeatation.setText("Every week");
		if (initValue == 30)
			tvRepeatation.setText("Every month");
	}

	private void initBackupTime() {
		String initValue = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_TIME, "12-12-2012 0:00");
		tvBackupTime.setText(initValue.substring(11));
	}

	public String Convert(String string) {
		String input = string;
		Date date = null;
		try {
			date = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.getDefault())
					.parse(input);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long milliseconds = date.getTime();
		return String.valueOf(milliseconds);
	}

	public String ConvertToDate(long milisecond) {
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy",
				Locale.getDefault());
		return formatter.format(milisecond);
	}
}
